import { _decorator, Component, Node, director, EventTouch, Input, Camera, v3, PhysicsSystem2D, v2, tween, Label } from 'cc';
import { DataManager } from '../Public/DataManager';
const { ccclass, property } = _decorator;

@ccclass('Barrier')
export class Barrier extends Component {
    isclick: boolean = false;
    start() {
        this.node.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
        this.initData();
    }
    onDestroy() {
        this.node.off(Input.EventType.TOUCH_START, this.onTouchStart, this)
    }

    update(deltaTime: number) {

    }
    /**返回主场景 */
    BackToMainScene() {
        director.loadScene(`MainScene`);
    }
    /**前往其他页面 */
    GotoPage(str: string) {
        const page = this.node.getChildByName(str);
        page.setPosition(0, 0);
    }
    /**场景点击事件 */
    onTouchStart(e: EventTouch) {
        if (this.isclick) {
            return;
        }
        this.isclick = true;
        const { x, y } = e.getLocation();
        const pos = v3();
        this.node.getComponentInChildren(Camera).screenToWorld(v3(x, y), pos);
        const res = PhysicsSystem2D.instance.testPoint(v2(pos.x, pos.y));
        if (res.length) {
            const { node } = res[0];
            const self = this;
            tween(node).by(0.1, { scale: v3(0.2, 0.2, 1) }).by(0.1, { scale: v3(-0.2, -0.2, 1) },
                {
                    onComplete() {
                        self.isclick = false;
                        self.GotoPage(node.name);
                    }
                }).start();
        }
        else
        {
            this.isclick = false;
        }
    }
    /**初始化数据 */
    initData() {
        let xhr = new XMLHttpRequest();
        const { threadID, duplicateID } = DataManager.Instance
        if (threadID && duplicateID) {
            return;
        }
        xhr.open(`post`, `https://2857e2g653.imdo.co/index.php/tpp/clearanceList`);
        xhr.setRequestHeader(`content-type`, `application/x-www-form-urlencoded`);
        xhr.setRequestHeader(`token`, `${DataManager.Instance.token}`);
        xhr.send(``);
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                const { code, data } = JSON.parse(xhr.response)
                if (code == 200) {
                    DataManager.Instance.threadID = data[0] ? data[0].clearance_id : null;
                    DataManager.Instance.duplicateID = data[1] ? data[1].clearance_id : null;
                }
            }
        }
    }
}

